import { createRouter, createWebHashHistory } from "vue-router";
import store from '@/store/index.js'
import np from 'nprogress'
const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: '/home',
            name: 'home',
            component: ()=> import('@/views/home/Home.vue'),
            children: [
                {
                    path: '/home',
                    name: '/home',
                    component: ()=> import('@/views/HomeIndex.vue'),
                    meta:{
                        title: '后台首页'
                    }
                },
                {
                    path: '/order/list',
                    name: 'orderList',
                    component: () => import('@/views/OrderList.vue'),
                    meta:{
                        title: '订单管理'
                    }
                }
            ]
        },
        {
            path: '/login',
            name: 'login',
            component: ()=> import('@/views/login/Login.vue')
        },
        // 捕获404路由
        {
            path: '/:pathMatch(.*)*',
            name: 'NotFound',
            component:()=>import('@/views/404.vue')    
        }
    ]
})

// 全局前置路由守卫
router.beforeEach(async (to, from, next) => {
    np.start()
    // 获取token
    const tokenStr = window.sessionStorage.getItem('token')
    if(tokenStr){
        await store.dispatch('getUserInfo')
    }
    // 如果没有登录
    if(!tokenStr && to.path !== '/login') return next('/login')
    // 如果已经登录
    if(tokenStr && to.path == '/login'){
        return next({ path: form.path? from.path : '/'})
    }
    next()
})

// 后置全局路由守卫
router.afterEach((to, from, next) => {
   np.done() 
})

export default router